
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_sliver_delegate/common_sliver_delegate.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/new_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_list_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/terminal_detail_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';

///选择播放终端页面
class MediaSelectTerminalPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "MediaSelectTerminalPage";

  final String hsns;
  ///是否是添加已有照片到终端
  final bool addTerminal;
  final String startday;
  final String endday;
  final String picid;
  final bool forceSelect;


  const MediaSelectTerminalPage({Key key, this.hsns, this.addTerminal,
    this.startday, this.endday, this.picid, this.forceSelect}):super(key: key);

  @override
  _MediaSelectTerminalPageState createState() => _MediaSelectTerminalPageState();

  ///跳转方法
  static Future<String> navigatorPush(
      BuildContext context, {String hsns, bool addTerminal, String startday,
      String endday, String picid, bool forceSelect}) {
    return RouterUtils.routeForFutureResult(
      context, MediaSelectTerminalPage(
      hsns: hsns,
      addTerminal: addTerminal,
      startday: startday,
      endday: endday,
      picid: picid,
      forceSelect: forceSelect,
    ),
      routeName: MediaSelectTerminalPage.ROUTER,
    );
  }
}

class _MediaSelectTerminalPageState extends BasePagerState<NewTerminalListItemBean, MediaSelectTerminalPage>
    with VgPlaceHolderStatusMixin{
  NewTerminalListViewModel _viewModel;
  TerminalDetailViewModel _detailViewModel;
  String _searchStr;
  bool _selectAll = false;
  String _hsns = "";
  @override
  void initState() {
    super.initState();
    _viewModel = NewTerminalListViewModel(this, searchStrFunc: () => _searchStr, allflg: "01");
    _detailViewModel = TerminalDetailViewModel(this, widget.hsns);
    _viewModel.refresh();
    _hsns = widget.hsns;
    VgEventBus.global.on().listen((event) {
      if(event is TerminalListRefreshEvent){
        _viewModel.refresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          children: <Widget>[
            _toTopBarWidget(),
            Expanded(
                child: MixinPlaceHolderStatusWidget(
                    errorOnClick: () => _viewModel?.refresh(),
                    emptyOnClick: () => _viewModel?.refresh(),
                    child: NestedScrollView(
                        headerSliverBuilder: (context, bool) {
                          return [
                            SliverPersistentHeader(
                              delegate: CommonSliverPersistentHeaderDelegate(
                                minHeight: 50,
                                maxHeight: 50,
                                child: Container(
                                  color: ThemeRepository.getInstance()
                                      .getCardBgColor_21263C(),
                                  padding: EdgeInsets.symmetric(vertical: 10),
                                  child:_toSearchWidget(),
                                ),
                              ),
                            ),
                          ];
                        },
                        body: _toListWidget()
                    ))
            ),
            _toConfirmWidget(),
          ],
        ),
      ),
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "请选择",
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  ///搜索
  Widget _toSearchWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        children: <Widget>[
          CommonSearchBarWidget(
            hintText: "搜索名字",
            // onChanged: (String searchStr) => _searchStr = searchStr,
            onSubmitted: (String searchStr) {
              _searchStr = searchStr;
              _viewModel?.refreshMultiPage();
            },
          ),
        ],
      ),
    );
  }

  ///图片展示栏
  Widget _toListWidget(){
    if(data != null){
      if(StringUtils.isNotEmpty(_hsns??"")){
        List<String> hsnList = _hsns.split(",");
        int count = 0;
        if(hsnList != null && hsnList.length > 0){

          data.forEach((element) {
            if(hsnList.contains(element.hsn)){
              element.selectStatus = true;
              count++;
            }
          });
        }
        if(count == data?.length??0){
          _selectAll = true;
        }
      }
    }
    return VgPullRefreshWidget.bind(
      state: this,
      viewModel: _viewModel,
      child: ListView.separated(
        padding: EdgeInsets.only(top: 0),
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index) {
          return _toListItemWidget(context, index, data?.elementAt(index));
        },
        separatorBuilder: (BuildContext context, int index){
          return SizedBox();
        },
        itemCount: data?.length??0,
      ),
    );
  }

  ///item
  Widget _toListItemWidget(BuildContext context, int index, NewTerminalListItemBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: ()  {
        setState(() {
          // if((widget?.forceSelect??false) && (itemBean.selectStatus??false) && _getHsns().split(",").length < 2){
          //   VgToastUtils.toast(context, '请至少选择一个终端');
          //   return;
          // }
          itemBean.selectStatus = !itemBean.selectStatus??false;
          _selectAll = _getSelectedCount() == data.length;
          _hsns = _getHsns();
        });
      },
      child: Container(
        height: 87,
        child: Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Image.asset(
                itemBean.selectStatus??false
                    ? "images/common_selected_ico.png"
                    : "images/common_unselect_ico.png",
                height: 20,
              ),
            ),

            Expanded(child: _toContentWidget(index, itemBean)),
          ],
        ),
      ),
    );
  }

  Widget _toContentWidget(int index, NewTerminalListItemBean itemBean) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              Visibility(
                visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
                child: Text(
                  // "硬件ID：",
                  "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  itemBean?.getTerminalName(index),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Spacer(),
              Visibility(
                child: Container(
                  alignment: Alignment.centerRight,
                  width: 60,
                  child: Text(
                    (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())?"已关机":"开机状态",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())
                          ?ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C()
                          :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Container(
            width: 236,
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(
            height: 4,
          ),
          Text(
            "管理员：${itemBean?.manager ?? "-"}${_getLoginStr(itemBean?.loginName) ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
          )
        ],
      ),
    );
  }

  String _getLoginStr(String loginName) {
    if (loginName == null || loginName == "") {
      return null;
    }
    return "（$loginName账号登录）";
  }

  int _getSelectedCount(){
    int count = 0;
    if(data != null){
      data.forEach((element) {
        if(element.selectStatus??false){
          count++;
        }
      });
    }
    return count;
  }

  ///确定
  Widget _toConfirmWidget(){
    return Container(
      height: 56,
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: (){
              setState(() {

                data.forEach((element) {
                  element.selectStatus = !_selectAll;
                });
                _selectAll = !_selectAll;
                _hsns = _getHsns();
              });
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Text(
                _selectAll?"全不选":"全选",
                style: TextStyle(
                  fontSize: 15,
                  color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                ),
              ),
            ),
          ),
          Visibility(
            visible: _getSelectedCount() > 0,
            child: Text(
              "已选${_getSelectedCount()}终端",
              style: TextStyle(
                fontSize: 12,
                color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              ),
            ),
          ),
          Spacer(),
          CommonFixedHeightConfirmButtonWidget(
            isAlive: true,
            height: 36,
            width: 90,
            margin: const EdgeInsets.symmetric(horizontal: 15),
            unSelectBgColor: Color(0xFF3A3F50),
            selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            unSelectTextStyle: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 15,
            ),
            selectedTextStyle: TextStyle(
              color: Colors.white,
              fontSize: 15,
              // fontWeight: FontWeight.w600
            ),
            text: "确定",
            onTap: (){
              if(widget?.addTerminal??false){
                if(StringUtils.isNotEmpty((widget?.hsns??"")) && StringUtils.isEmpty(_getHsns())){
                  //取消所有选择的终端，走取消接口
                  _detailViewModel.cancelFolder(context, widget?.picid);

                }else{
                  _viewModel.addMediaToTerminals(context, (_getSelectedCount() == data?.length)?"01":"00",
                      widget?.startday, widget?.endday, _getHsns(), widget?.picid);
                }
              }else{
                if((widget?.forceSelect??false) && StringUtils.isEmpty(_getHsns())){
                  VgToastUtils.toast(context, '请至少选择一个终端');
                  return;
                }
                RouterUtils.pop(context, result: _getHsns());
              }

            },
          ),
        ],
      ),
    );
  }

  String _getHsns(){
    String hsns = "";
    data.forEach((element) {
      if(element.selectStatus){
        hsns += element.hsn;
        hsns += ",";
      }
    });
    if(StringUtils.isNotEmpty(hsns)){
      hsns = hsns.substring(0, hsns.length-1);
    }
    return hsns;
  }



}